<template>
  <div class="confirmation-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="开单确认"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 确认内容 -->
    <div class="confirmation-content">
      <!-- 申请信息 -->
      <div class="info-section">
        <h3 class="section-title">申请信息</h3>
        <div class="info-card">
          <div class="info-row">
            <span class="info-label">申请医院</span>
            <span class="info-value">{{ orderData.hospital?.name || '四川省保健院北苑' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请人</span>
            <span class="info-value info-link" @click="openApplicantPicker">
              <span class="applicant-name">{{ selectedApplicant }}</span>
              <van-icon name="arrow" class="arrow-icon" />
            </span>
          </div>
        </div>
      </div>

      <!-- 申请原因 -->
      <div class="reason-section">
        <div class="reason-header">
          <span class="reason-title">申请原因</span>
          <span class="reason-required">*</span>
        </div>
        <van-field
          v-model="applicationReason"
          type="textarea"
          placeholder="请输入项目申请原因用于医生更准确判断，不少于20字"
          rows="3"
          maxlength="200"
          show-word-limit
          class="reason-textarea"
        />
      </div>

      <!-- 检查项目详情 -->
      <div class="projects-section">
        <h3 class="section-title">检查项目详情</h3>
        <div class="projects-list">
          <div 
            v-for="item in orderData.items" 
            :key="item.id"
            class="project-item"
          >
            <div class="project-info">
              <div class="project-header">
                <span class="project-name">{{ item.name }}</span>
                <span class="project-type" :class="getProjectTypeClass(item.category)">{{ getProjectTypeText(item.category) }}</span>
              </div>
              <div class="project-details">
                <div class="project-desc">{{ item.description }}</div>
                <div class="project-meta">
                  <span class="project-quantity">数量：{{ item.quantity || '1' }}项</span>
                  <span class="project-unit-price">单价：¥{{ item.price.toFixed(2) }}</span>
                </div>
              </div>
            </div>
            <div class="project-total">
              <div class="total-label">小计</div>
              <div class="total-price">¥{{ (item.price * (Number(item.quantity) || 1)).toFixed(2) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 费用汇总 -->
        <div class="cost-summary">
          <div class="summary-row">
            <span class="summary-label">项目总数</span>
            <span class="summary-value">{{ orderData.items.length }}项</span>
          </div>
          <div class="summary-row">
            <span class="summary-label">检查费用</span>
            <span class="summary-value">¥{{ totalAmount }}</span>
          </div>
          <div class="summary-row total-row">
            <span class="summary-label">合计金额</span>
            <span class="summary-value total-amount">¥{{ totalAmount }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="confirmation-footer">
      <div class="footer-info">
        <div class="total-info">
          <span class="total-label">总计</span>
          <span class="total-value">¥{{ totalAmount }}</span>
        </div>
      </div>
      <div class="footer-buttons">
        <van-button 
          type="default" 
          size="large" 
          @click="goBackToModify"
          class="back-btn"
        >
          返回修改
        </van-button>
        <van-button 
          type="primary" 
          size="large" 
          @click="confirmOrder"
          class="confirm-btn"
        >
          确认开单
        </van-button>
      </div>
    </div>

    <!-- 申请人选择弹窗 -->
    <van-popup
      v-model:show="showApplicantPicker"
      position="bottom"
      round
      :style="{ height: '40%' }"
    >
      <van-picker
        :columns="applicantOptions"
        @confirm="onApplicantConfirm"
        @cancel="showApplicantPicker = false"
        title="选择申请人"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { apiService, type SubmitOrderApplicationRequest } from '@/api'
import { useUserStore } from '@/stores/user'

/**
 * 开单确认页面组件
 * 显示申请信息、申请原因和申请项目，用户确认后进入支付页面
 */

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

/**
 * 申请人选择相关
 */
const selectedApplicant = ref('王小明')
const showApplicantPicker = ref(false)
const applicantOptions = ref([
  '王小明',
  '李小红', 
  '张小华',
  '刘小强',
  '陈小美'
])

/**
 * 申请原因
 */
const applicationReason = ref('')

/**
 * 订单项目接口
 */
interface OrderItem {
  id: number
  name: string
  description: string
  price: number
  category?: string
  quantity?: string
  tags?: string[]
}

/**
 * 订单数据接口
 */
interface OrderData {
  items: OrderItem[]
  hospital?: {
    name: string
    address?: string
  }
  applicant?: string
  reason?: string
  totalAmount?: string
}

/**
 * 订单数据
 */
const orderData = ref<OrderData>({
  items: [],
  hospital: {
    name: '四川省保健院北苑',
    address: '成都市金牛区'
  },
  applicant: '王小明',
  reason: '请输入项目申请原因用于医生更准确判断，不少于20字'
})

/**
 * 计算总金额
 */
const totalAmount = computed(() => {
  return orderData.value.items.reduce((sum, item) => sum + item.price, 0).toFixed(2)
})

/**
 * 点击返回按钮
 */
const onClickLeft = () => {
  Dialog.confirm({
    title: '确认返回',
    message: '返回将丢失当前申请信息，确认返回吗？',
    confirmButtonText: '确认返回',
    cancelButtonText: '继续申请'
  }).then(() => {
    router.back()
  }).catch(() => {
    // 用户取消返回
  })
}

/**
 * 获取项目类型样式类
 * @param category 项目分类
 */
const getProjectTypeClass = (category?: string) => {
  const classMap: Record<string, string> = {
    'lab': 'type-lab',
    'exam': 'type-exam',
    'medicine': 'type-medicine'
  }
  return classMap[category || 'lab'] || 'type-lab'
}

/**
 * 获取项目类型文本
 * @param category 项目分类
 */
const getProjectTypeText = (category?: string) => {
  const textMap: Record<string, string> = {
    'lab': '检验',
    'exam': '检查',
    'medicine': '药品'
  }
  return textMap[category || 'lab'] || '检验'
}

/**
 * 格式化日期
 * @param date 日期对象
 */
const formatDate = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/**
 * 打开申请人选择器
 */
const openApplicantPicker = () => {
  console.log('点击申请人选择区域')
  showApplicantPicker.value = true
  console.log('申请人选择器状态:', showApplicantPicker.value)
}

/**
 * 申请人选择确认
 * @param value 选择的申请人信息
 * @param index 选择的索引
 */
const onApplicantConfirm = (selectedValues: string[], selectedIndexes: number[]) => {
  console.log('申请人选择确认事件触发:', { selectedValues, selectedIndexes })
  
  // Vant Picker组件确认时，第一个参数是选中的值数组，第二个参数是索引数组
  if (selectedValues && selectedValues.length > 0) {
    // 直接使用选中的字符串值
    selectedApplicant.value = selectedValues[0]
    showApplicantPicker.value = false
    console.log('选择申请人成功:', selectedApplicant.value)
  } else {
    console.error('申请人选择数据格式错误:', { selectedValues, selectedIndexes })
    Toast('申请人选择失败，请重试')
  }
}

/**
 * 返回修改
 */
const goBackToModify = () => {
  Dialog.confirm({
    title: '返回修改',
    message: '返回将重新进入开单申请页面，您可以修改选择的检查项目，确认返回吗？',
    confirmButtonText: '确认返回',
    cancelButtonText: '继续确认'
  }).then(() => {
    // 返回到开单申请页面
    router.push('/order-application')
  }).catch(() => {
    // 用户取消返回
  })
}

/**
 * 确认开单
 */
const confirmOrder = async () => {
  // 验证申请原因
  if (!applicationReason.value.trim()) {
    Toast('请填写申请原因')
    return
  }

  if (applicationReason.value.trim().length < 20) {
    Toast('申请原因不少于20字')
    return
  }

  // 验证申请人
  if (!selectedApplicant.value) {
    Toast('请选择申请人')
    return
  }

  Dialog.confirm({
    title: '确认开单',
    message: `请仔细核对以下信息：\n\n申请人：${selectedApplicant.value}\n检查项目：共${orderData.value.items.length}项\n合计费用：¥${totalAmount.value}\n\n确认无误后将正式生成开单记录并进入支付流程`,
    confirmButtonText: '确认开单',
    cancelButtonText: '再次检查'
  }).then(async () => {
    try {
      Toast.loading({
        message: '正在生成开单记录...',
        forbidClick: true,
        duration: 0
      })
      
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        Toast('请先登录后再进行开单操作')
        router.push('/login')
        return
      }

      // 构造提交开单申请的数据
      const submitData: SubmitOrderApplicationRequest = {
        userId: userStore.userId,
        hospitalAreaId: 1, // 默认院区ID
        contactPhone: userStore.userInfo?.phone || '13800138000',
        remarks: applicationReason.value.trim(),
        items: orderData.value.items.map(item => ({
          medicalProjectId: item.id,
          quantity: parseInt(item.quantity || '1')
        }))
      }
      
      // 调用后端API提交开单申请
      const response = await apiService.submitOrderApplication(submitData)
      
      Toast.clear()
      
      if (response.code === 200 && response.data) {
        Toast.success({
          message: '开单记录生成成功！',
          duration: 1000
        })
        
        // 跳转到支付页面，传递订单ID
        setTimeout(() => {
          goToPayment(response.data.id, response.data.applicationNumber)
        }, 1000)
      } else {
        Toast.fail(response.message || '开单申请提交失败，请重试')
      }
    } catch (error) {
      Toast.clear()
      console.error('提交开单申请失败:', error)
      Toast.fail('网络错误，请稍后重试')
    }
  }).catch(() => {
    // 用户取消确认
  })
}

/**
 * 跳转到支付页面
 * @param orderId 订单ID
 * @param orderNumber 订单编号
 */
const goToPayment = (orderId: number, orderNumber: string) => {
  // 构造支付页面需要的订单数据
  const paymentData = {
    orderId: orderId, // 添加订单ID
    orderNumber: orderNumber, // 添加订单编号
    userId: 4, // 添加用户ID，与提交开单申请时保持一致
    items: orderData.value.items.map(item => ({
      id: item.id,
      name: item.name,
      description: item.description,
      price: item.price
    })),
    hospital: orderData.value.hospital,
    applicant: selectedApplicant.value,
    reason: applicationReason.value,
    totalAmount: totalAmount.value
  }
  
  // 跳转到支付页面，携带订单数据
  router.push({
    path: '/order-payment',
    query: {
      orderData: JSON.stringify(paymentData)
    }
  })
}

/**
 * 从路由参数加载订单数据
 */
const loadOrderData = () => {
  try {
    const orderDataStr = route.query.orderData as string
    if (orderDataStr) {
      const data = JSON.parse(orderDataStr)
      orderData.value = {
        ...orderData.value,
        ...data
      }
      
      // 加载申请人信息
      if (data.applicant) {
        selectedApplicant.value = data.applicant
      }
      
      // 加载申请原因
      if (data.reason) {
        applicationReason.value = data.reason
      }
      
      console.log('加载确认页面数据:', data)
    } else {
      // 如果没有订单数据，使用默认数据进行演示
      orderData.value.items = [
        {
          id: 1,
          name: '新冠预防中药（正常人群）',
          description: '预防新冠病毒感染的中药制剂',
          price: 11.80,
          category: 'medicine',
          quantity: '1剂',
          tags: ['处方药', '限购5剂']
        },
        {
          id: 2,
          name: '云南白药胶囊 0.5g*20片',
          description: '用于跌打损伤，瘀血肿痛',
          price: 10.08,
          category: 'medicine',
          quantity: '1盒',
          tags: ['外方药']
        }
      ]
      
      // 即使没有完整订单数据，也要尝试从路由参数获取医院信息
      const { hospitalName, hospitalAddress } = route.query
      if (hospitalName) {
        orderData.value.hospital = {
          name: hospitalName as string,
          address: hospitalAddress as string || ''
        }
        console.log('从路由参数加载医院信息:', orderData.value.hospital)
      }
    }
  } catch (error) {
    console.error('解析订单数据失败:', error)
    Toast('订单数据加载失败')
    router.back()
  }
}

/**
   * 页面挂载时初始化数据
   */
  onMounted(() => {
    console.log('开单确认页面已加载')
    userStore.initUserInfo()
    loadOrderData()
  })
</script>

<style scoped>
.confirmation-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
  position: relative; /* 为绝对定位的按钮栏提供定位上下文 */
  /* 移除 overflow: hidden，允许页面滚动 */
}

.confirmation-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

/* 通用样式 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 16px 12px;
}

/* 申请信息样式 */
.info-section {
  margin: 20px 16px;
}

.info-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  min-height: 40px; /* 确保有足够的高度 */
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* 申请人选择样式 */
.info-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #333;
  gap: 8px; /* 姓名和箭头之间的间距 */
}

.info-link .applicant-name {
  white-space: nowrap;
  overflow: visible; /* 允许文本完全显示 */
  text-overflow: clip;
  min-width: 80px; /* 确保最小宽度 */
  max-width: none !important; /* 强制移除最大宽度限制，覆盖全局样式 */
  width: auto !important; /* 确保宽度自适应内容 */
  flex-shrink: 0; /* 防止被flex布局压缩 */
}

.arrow-icon {
  color: #c8c9cc;
  font-size: 12px;
}

/* 申请原因样式 */
.reason-section {
  margin: 20px 16px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.reason-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.reason-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.reason-required {
  color: #ff4757;
  margin-left: 4px;
  font-size: 16px;
}

.reason-textarea {
  width: 100%;
}

:deep(.reason-textarea .van-field__control) {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #e1e8ed;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
}

:deep(.reason-textarea .van-field__control:focus) {
  border-color: #1989fa;
  background: #fff;
}

:deep(.reason-textarea .van-field__word-limit) {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

/* 申请项目样式 */
.projects-section {
  margin: 0 16px 20px;
}

.projects-list {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 12px;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.project-item:last-child {
  border-bottom: none;
}

.project-info {
  flex: 1;
  margin-right: 16px;
}

.project-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.project-type {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  color: #fff;
  font-weight: 500;
}

.type-lab {
  background-color: #1989fa;
}

.type-exam {
  background-color: #07c160;
}

.type-medicine {
  background-color: #ff6b35;
}

.project-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.project-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.project-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.project-meta {
  display: flex;
  gap: 16px;
  align-items: center;
}

.project-quantity,
.project-unit-price {
  font-size: 12px;
  color: #999;
}

.project-total {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  text-align: right;
}

.total-label {
  font-size: 12px;
  color: #999;
}

.total-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

/* 费用汇总样式 */
.cost-summary {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.total-row {
  border-top: 1px solid #eee;
  padding-top: 12px;
  margin-top: 8px;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.total-amount {
  font-size: 18px !important;
  font-weight: bold !important;
  color: #ff6b35 !important;
}

/* 底部确认按钮样式 */
.confirmation-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  /* 确保在手机屏幕内 */
  max-width: 100%;
  box-sizing: border-box;
  /* 确保按钮在最上层，可以被点击 */
  z-index: 1000;
  /* 确保按钮区域可以接收点击事件 */
  pointer-events: auto;
}

.footer-info {
  flex: 1;
}

.total-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}

.total-label {
  font-size: 12px;
  color: #999;
  font-weight: 400;
  line-height: 1;
}

.total-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b35;
  line-height: 1.2;
}

.footer-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.back-btn {
  min-width: 80px;
  height: 44px;
  border-radius: 22px;
  font-weight: bold;
  border: 1px solid #ebedf0;
  color: #646566;
  background: white;
  pointer-events: auto;
  position: relative;
  z-index: 1001;
}

.confirm-btn {
  min-width: 120px;
  height: 44px;
  border-radius: 22px;
  font-weight: bold;
  /* 确保按钮可以被点击 */
  pointer-events: auto;
  /* 确保按钮在合适的层级 */
  position: relative;
  z-index: 1001;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .confirmation-content {
    padding: 12px;
  }
  
  .info-card,
  .reason-card,
  .projects-list,
  .cost-summary {
    padding: 12px;
  }
  
  .confirmation-footer {
    padding: 8px 12px;
  }
  
  .project-item {
    padding: 12px;
  }
}
</style>